package com.caine.androidtask.ls20;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.net.Uri;
import android.util.Log;

import com.caine.androidtask.R;

public class FileHelper {

	public static List<Beans> getFilesList(String path) {
		if (path == null || path.equals(""))
			return null;

		List<Beans> list = new ArrayList<Beans>();
		File file = new File(path);
		try {
			File[] li = file.listFiles();
			for (File f : li) {
				Beans bean = new Beans();
				bean.setName(f.getName());
				bean.setPath(f.getPath());
				bean.setType(getFileType(f));
				bean.setIcon(getFileIcon(getFileType(f)));
				list.add(bean);
			}
		} catch (Exception e) {
			return null;
		}

		return list == null ? null : list;
	}

	public static String getFileType(File f) {
		String type = "";
		if (f.isDirectory())
			return "folder";
		
		String end = f.getName().substring(f.getName().lastIndexOf('.') + 1).toLowerCase();
		if (end.equals("apk")) {
			return "application/vnd.android.package-archive";
		} else if (end.equals("mp4") || end.equals("avi") || end.equals("3gp")
				|| end.equals("rmvb")) {
			type = "video";
		} else if (end.equals("m4a") || end.equals("mp3") || end.equals("mid") || end.equals("xmf")
				|| end.equals("ogg") || end.equals("wav")) {
			type = "audio";
		} else if (end.equals("jpg") || end.equals("gif") || end.equals("png")
				|| end.equals("jpeg") || end.equals("bmp")) {
			type = "image";
		} else if (end.equals("txt") || end.equals("log")) {
			type = "text";
		} else {
			type = "*";
		}
		type += "/*";
		//Log.e("CaineZhu", "CaineZhu===> fileType : "+type);
		return type;

	}

	public static int getFileIcon(String type) {

		if (type.equals("folder")) {
			return R.drawable.folder;
		} else if (type.equals("application/vnd.android.package-archive")) {
			return R.drawable.apkicon;
		} else if (type.equals("audio/*")) {
			return R.drawable.format_music;
		} else if (type.equals("text/*")) {
			return R.drawable.note_editor;
		} else if (type.equals("video/*")) {
			return R.drawable.format_media;
		} else if (type.equals("image/*") ) {
			return R.drawable.format_picture;
		} else {
			return R.drawable.file;
		}
	}
	
	
	public static Intent openFile(String path){
		Intent intent = new Intent();
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(Intent.ACTION_VIEW);
		File f = new File(path);
		String type = getFileType(f);
		intent.setDataAndType(Uri.fromFile(f), type);		
		return intent;
	}

}
